package com.gitee.btssplib

import android.util.Log
import io.reactivex.Flowable
import io.reactivex.functions.Function
import org.reactivestreams.Publisher
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger

/**
 * 重试功能.
 * @author John
 * @version 1.0
 */

class RetryFunction(

        private val retryCount: Int = 3,
        private val delaySeconds: Long = 5

) : Function<Flowable<Throwable>, Publisher<*>> {

    companion object {
        val TAG = "RetryFunction"
    }

    @Throws(Exception::class)
    override fun apply(throwableFlowable: Flowable<Throwable>): Publisher<*>? {
        Log.d(TAG, "Applying function ...")

        val counter = AtomicInteger()
        return throwableFlowable.takeWhile {
            val count = counter.getAndIncrement()
            val result = count < retryCount
            Log.d(TAG, "判断是否达到重试上限：${!result}")
            result
        }.flatMap { error ->
            val count = counter.get()
            Log.d(TAG, "当前尝试次数：$count")
            if (count < retryCount) {
                Log.d(BTConnector.TAG, "${delaySeconds}秒后重试")
                Flowable.timer(delaySeconds, TimeUnit.SECONDS)
            } else {
                Flowable.error(error)
            }
        }
    }
}
